package com.jhy.new2025.BinaryTree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 根左右
 * 用栈实现遍历（迭代遍历）
 */
public class preorderTraversal2 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) return res;
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            res.add(pop.val);//根
            if (pop.right != null) stack.push(pop.right);// 右
            if (pop.left != null) stack.push(pop.left); // 左
        }
        return res;
    }
}
